<template>
  <!-- 取款账号 -->
  <div class="information-content-h5">
    <h1 class="information-content-h5__title">
      <h3 @click="goBack"><i-teenyicons-arrow-left-solid /> {{ title }}</h3>
    </h1>
    <div class="withdrawal-account-h5">
      <van-tabs v-model:active="active" @change="changeTabs">
        <van-tab :title="item.title" v-for="item in navs" :key="item.active"></van-tab>
      </van-tabs>
      <div class="withdrawal-account-wrapper" v-if="active === 0">
        <div class="withdrawal-account-wrapper__card" v-for="item in bankOfThird" :key="item.id">
          <div class="pay-banks__item-header">
            <img :src="images.icon" alt="">
            <span>{{item.bankAccount}}</span>
            <div class="pay-checkbox">
              <span>{{ t('userData.default') }}</span>
              <el-checkbox v-model="item.default" @change="handleSetDefaultBank($event, item)" class="normal"/>
            </div>
          </div>
          <div class="pay-banks__item-number">{{item.bankNumber}}</div>
          <div class="pay-banks__item-footer"><span>PIX</span> <em @click="unbind(item)">{{ t('userData.cancelBind') }}</em></div>
        </div>
        <div class="withdrawal-account-wrapper__card add-bank" @click="bandBank('third')">
          <img :src="images.updatedark" v-if="piniaSystem.getDarkTheme" alt="">
          <img :src="images.updatelight" v-else alt="">
          {{ t('userData.binding1') }}
        </div>
      </div>
      <div class="withdrawal-account-wrapper" v-if="active === 1">
        <div class="withdrawal-account-wrapper__card" v-for="item in bankOfDigital" :key="item.id">
          <div class="pay-banks__item-header">
            <img :src="images.icon" alt="">
            <span>{{item.bankAccount}}</span>
            <div class="pay-checkbox">
              <span>{{ t('userData.default') }}</span>
              <el-checkbox v-model="item.default" @change="handleSetDefaultBank($event, item)" class="normal"/>
            </div>
          </div>
          <div class="pay-banks__item-number">{{item.bankNumber}}</div>
          <div class="pay-banks__item-footer"><span>PIX</span> <em @click="unbind(item)">{{ t('userData.cancelBind') }}</em></div>
        </div>
        <div class="withdrawal-account-wrapper__card add-bank" @click="bandBank('third')">
          <img :src="images.updatedark" v-if="piniaSystem.getDarkTheme" alt="">
          <img :src="images.updatelight" v-else alt="">
          {{ t('userData.binding2') }}
        </div>
      </div>
    </div>
    <!-- 底部弹出 -->
    <van-popup
      v-model:show="showBind"
      position="bottom"
      :style="{ height: '65%' }"
    >
      <div class="bind-popup-wrapper">
        <h1 class="bind-popup-title">{{ navs[active].title }}</h1>
        <h2 class="bind-popup-title__header" v-if="navs[active].active === 'thirdPay'">{{t('userData.platform01')}}: {{t('userData.platform02')}}</h2>
        <el-form :model="form" ref="formRef" :rules="rules" label-position="top" size="small">
          <el-form-item prop="bankAccountName">
            <el-input v-model="form.bankAccountName" readonly placeholder="" @focus="showBank = true" :suffix-icon="ArrowDown"/>
          </el-form-item>
          <el-form-item prop="bankNumber">
            <el-input v-model="form.bankNumber" placeholder=""/>
          </el-form-item>
          <el-form-item>
            <div class="pay-checkbox">
              <span>{{ t('userData.asDefault') }}</span>
              <el-checkbox v-model="form.default" class="normal"/>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="h5-popup-search-button" @click="bindBank">{{t('userData.saveBtn')}}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </van-popup>

    <van-popup
      v-model:show="showBank"
      position="bottom"
    >
      <van-picker
        :columns="active == 0 ? bankList : digitalList"
        :columns-field-names="{text: 'name', value: 'id'}"
        v-model="bankAccount"
        :option-height="`100rem`"
        @confirm="onConfirmWallet"
        @cancel="closeWalletForPcOrH5"
      >
        <template #option="scope">
          {{ scope.name }}
        </template>
      </van-picker>
    </van-popup>
  </div>
</template>

<script setup lang="ts" name="ChangePaswordH5">
import userinfoApi from '@/api/modules/userinfo';
import userinfo from '@/store/userinfo';
import system from '@/store/system';
import { ArrowDown } from '@element-plus/icons-vue';
import nocache from '@/store/nocache';

const global:any = getCurrentInstance()?.appContext.config.globalProperties;
const { t } = useI18n();
const emits = defineEmits(['back']);
const piniaUserinfo:any = userinfo();
const piniaSystem:any = system();
const piniaNocache:any = nocache();

const props = defineProps({
  title: {
    type: String,
    default: ""
  }
});

const images: any = reactive({
  icon: new URL(`../../assets/images/bank/icon.png`, import.meta.url).href,
  updatedark: new URL(`../../assets/images/bank/update-dark.png`, import.meta.url).href,
  updatelight: new URL(`../../assets/images/bank/update-light.png`, import.meta.url).href,
});

const data:any = reactive({
  navs: [
    {
      title: t('userData.thirdPay'),
      active: 'thirdPay',
    },
    {
      title: t('userData.currencyNum'),
      active: 'currencyNum',
    }
  ],
  active: 0,
  bankOfThird: [],
  bankOfDigital: [],
  showBind: false,
  showBank: false,
  bankList: [
    {
      name: "CNPJ",
      id: "CNPJ"
    },
    {
      name: "CPF",
      id: "CPF"
    },
    {
      name: "EMAIL",
      id: "EMAIL"
    },
    {
      name: "PHONE",
      id: "PHONE"
    },
  ],
  bankAccount: [],
  digitalList: computed(()=> piniaUserinfo.getDigitalWallet.filter((im:any)=>im.platformType === 1)),
  form: {
    default: true
  },
  rules: {
    bankAccountName: [
      { required: true, message: computed(()=>t('userData.chooseType')), trigger: 'change' },
    ],
    bankNumber: [
      { required: true, message: computed(()=>t('WALLET.AccountRule')), trigger: 'blur' },
      { validator: (rule: any, value: any, callback: any) => {
        if (value === '') {
          callback(new Error(t('WALLET.AccountRule')))
        } else if (form.value.bankAccountName === 'CPF' && !/^\d{11}$/.test(value)) {
          callback(t('userData.CPFRule'))
        } else if (form.value.bankAccountName === 'CNPJ' && !/^\d{14}$/.test(value)) {
          callback(t('userData.CNPJRule'))
        } else if (form.value.bankAccountName === 'EMAIL' && !/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
          callback(t('Message.code_1001'))
        } else if (form.value.bankAccountName.indexOf('BSC') >= 0 && !/^[\d\w]{42}$/.test(value)) {
          callback(t('userData.inputWalletAddress').replace('#', `42`))
        }  else if (form.value.bankAccountName.indexOf('TRC') >= 0 && !/^[\d\w]{34}$/.test(value)) {
          callback(t('userData.inputWalletAddress').replace('#', `34`))
        } else {
          callback()
        }
      }, trigger: 'blur' },
    ],
  },
  formRef: null,
});

const {
  navs,
  active,
  bankOfThird,
  bankOfDigital,
  showBind,
  showBank,
  bankList,
  digitalList,
  bankAccount,
  form,
  rules,
  formRef,
} = toRefs(data);

// 获取银行卡
const getUserBank = (bankType: number) => {
  piniaNocache.setLoading(true);
  userinfoApi.getUserBank({
    bankType: bankType
  }).then((response:any)=>{
    if(response.code === 200){
      response.data.forEach((element:any) => {
        element.default = element.bankDefault === 1 ? true : false;
      });
      if(bankType == 2){
        bankOfThird.value = response.data || [];
      }else if(bankType == 1){
        bankOfDigital.value = response.data || [];
      }
    }
  }).finally(()=>{
    piniaNocache.setLoading(false);
  });
}
getUserBank(2);

// 切换支付方式
const changeTabs = () => {
  if(active.value == 0){
    piniaUserinfo.setDigitalWallet();
  }else{
    piniaUserinfo.setDigitalWallet('1005');
  }
  getUserBank(active.value == 0 ? 2 : 1);
}

// 绑定默认
const handleSetDefaultBank = (val: any, bank: any) => {
  piniaNocache.setLoading(true);
  userinfoApi.upUserBank(Object.assign(bank, {
    bankDefault: 1
  })).then((response:any)=>{
    if(response.code === 200){
      global.message(response.msg);
      getUserBank(bank.bankType);
    }
  }).finally(()=>{
    piniaNocache.setLoading(false);
  });
}

// 解绑
const unbind = (bank: any) => {
  piniaNocache.setLoading(true);
  userinfoApi.upUserBank(Object.assign(bank, {
    flag: 1
  })).then((response:any)=>{
    if(response.code === 200){
      global.message(response.msg);
      getUserBank(bank.bankType);
    }
  }).finally(()=>{
    piniaNocache.setLoading(false);
  });
}

// ---- 确认选择
const onConfirmWallet = ({selectedOptions}:any) => {
  form.value.bankAccount = bankAccount.value;
  form.value.bankAccountName = selectedOptions[0].name;
  showBank.value = false;
}

// ---- 取消选择
const closeWalletForPcOrH5 = (v:any) => {
  showBank.value = false;
}

// 打开绑定银行卡
const bandBank = (type: string) => {
  form.value.bankAccount = null;
  form.value.bankAccountName = null;
  showBind.value = true;
  form.value = {
    default: true
  }
}

// 绑定银行卡
const bindBank = () => {
  formRef.value.validate((valid:any, fields:any) => {
    if (valid) {
      showBind.value = false;
      piniaNocache.setLoading(true);
      let bankType = active.value === 0 ? 2 : 1;
      userinfoApi.addUserBank({
        bankAccount: form.value.bankAccountName,
        bankArea: piniaSystem.getLang.countryCode,
        bankDefault: form.value.default ? 1 : 0,
        bankNumber: form.value.bankNumber,
        bankType: bankType,
      }).then((response:any)=>{
        if(response.code === 200){
          global.message(response.msg);
          getUserBank(bankType);
        }
      }).finally(()=>{
        piniaNocache.setLoading(false);
      });
    }
  });
}


const goBack = () => {
  emits('back');
}
</script>

<style lang="scss" scoped>
@import url(./index.scss);
.withdrawal-account-h5{
  margin: var(--rem-20) 0;
  .withdrawal-account-wrapper{
    margin: 0 var(--rem-40);
    padding: var(--rem-5) 0;
    .withdrawal-account-wrapper__card{
      margin: var(--rem-20) 0;
      padding: var(--rem-15);
      height: var(--rem-150);
      border-radius: var(--rem-15);
      box-sizing: border-box;
      background: url(../../assets/images/bank/bgImg.png) no-repeat;
      background-size: cover;
      &.add-bank{
        height: var(--rem-150);
        border-radius: var(--rem-16);
        background: none;
        border: 1px dashed var(--z-border-def);
        font-size: var(--rem-14);
        color: var(--z-font-def);
        align-items: center;
        justify-content: center;
        cursor: pointer;
        display: flex;
        flex-direction: column;
        img{
          width: var(--rem-43);
          height: var(--rem-43);
          margin-bottom: var(--rem-10);
        }
      }
      .pay-banks__item-header{
        display: flex;
        align-items: center;
        color: white;
        &>span{
          font-size: var(--rem-20);
          margin-left: var(--rem-10);
        }
        &>img{
          display: block;
          width: var(--rem-39);
        }
      }
      .pay-banks__item-number{
        flex-grow: 1;
        word-break: break-all;
        font-size: var(--rem-18);
        line-height: var(--rem-17);
        color: white;
        height: var(--rem-70);
        display: flex;
        align-items: flex-end;
        padding-bottom: var(--rem-20);
      }
      .pay-banks__item-footer{
        display: flex;
        justify-content: space-between;
        span{
          font-size: var(--rem-14);
          color: white;
          opacity: 0.6;
        }
        em{
          font-size: var(--rem-14);
          cursor: pointer;
          text-decoration: underline;
          color: white;
        }
      }
    }
  }
}
.bind-popup-wrapper{
  padding: var(--rem-30) var(--rem-25);
}
.bind-popup-title{
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: var(--rem-15);
  color: var(--z-font-anti);
}
.bind-popup-title__header{
  display: flex;
  font-size: var(--rem-13);
  margin-top: var(--rem-20);
}
.pay-checkbox{
  display: flex;
  align-items: center;
  font-size: var(--rem-12);
  margin-left: auto;
  span{
    color: white;
    opacity: 0.6;
    white-space: nowrap;
    margin-right: var(--rem-10);
  }
}
</style>
